import fgdc_mysql
import sys
import os
import subprocess
import shutil
import Image
import pil_plugins
import amara

def process(img_dir, http_prefix, kml_dir, fgdc_dir, mrsidgeodecode,
                gdal2tiles,
                db_hostname, db_name, db_username, db_password,
                progress, recursive, image_type):
    if recursive:
        for root, dirs, files in os.walk(img_dir):
            process_dir(root, http_prefix, kml_dir, fgdc_dir, mrsidgeodecode,
                        gdal2tiles,
                        db_hostname, db_name, db_username, db_password,
                        progress, image_type)
    else:
        process_dir(img_dir, http_prefix, kml_dir, fgdc_dir, mrsidgeodecode,
                    gdal2tiles,
                    db_hostname, db_name, db_username, db_password,
                    progress, image_type)

def extract_title(fgdc_filename):
    doc = amara.parse(open(fgdc_filename, 'r'))
    return str(doc.metadata.idinfo.citation.citeinfo.title)

def process_dir(img_dir, http_prefix, kml_dir, fgdc_dir, mrsidgeodecode,
                gdal2tiles,
                db_hostname, db_name, db_username, db_password,
                progress, image_type):

    filelist = os.listdir(img_dir)
    progress.setMaximum(len(filelist))
    progress.setValue(1)

    for filename in filelist:
        img_name = filename[:-4]

        progress.setLabelText("Publishing")
        progress.setValue(progress.value()+1)
        
        if progress.wasCanceled():
            break

        print img_name

        if filename.lower().endswith(image_type):
            # Check for an XML file.
            fgdc_filename = os.path.join(img_dir, img_name) + ".sid.xml"
            if not os.path.exists(fgdc_filename):
                print "Could not find FGDC file for " + filename
                continue

            # Convert SID to TIFF.
            print "Converting %s " % os.path.join(img_dir, filename)
            subprocess.call([mrsidgeodecode, '-i', os.path.join(img_dir, filename),
                             '-o', os.path.join(img_dir, img_name) + '.tif',
                             '-of', 'tifg'])
            shutil.copy(os.path.join(img_dir, img_name) + '.sdw',
                        os.path.join(img_dir, img_name) + '.tfw')

            # Convert TIFF to RGB format.
            tiff = Image.open(os.path.join(img_dir, img_name) + '.tif')
            rgb_tiff = tiff.convert('RGB')
            rgb_tiff.save(os.path.join(img_dir, img_name) + '.tif')

            errcode = subprocess.call([gdal2tiles,
                                       '-publishurl',
                                       http_prefix,
                                       '-forcekml',
                                       '-title',
                                       extract_title(fgdc_filename),
                                       os.path.join(img_dir, img_name) + '.tif',
                                       os.path.join(kml_dir, img_name)])

#            os.remove(os.path.join(img_dir, img_name) + '.tif')

            fgdc_doc = fgdc_mysql.open_fgdc_xml(fgdc_filename)

            fgdc_mysql.insert_kml_url(http_prefix + img_name + "/" + img_name + ".kml", 
                                      fgdc_doc)
            
            fgdc_mysql.fgdc_to_db(fgdc_doc, db_hostname, db_name, db_username, db_password)
            
            fgdc_outfile = open(os.path.join(fgdc_dir, img_name) + '.xml' , 'w')
            fgdc_outfile.write(fgdc_doc.xml())
            fgdc_outfile.close()
